// 接口只能引入这个文件，在app.vue里导入过，导入第2个js文件找不到，不清楚原因
import authRequest from '@/api/identity/auth.js'
import { showLoading, hideLoading, getUrlParams, showErrorPop } from '@/utils/common'

const setToken = (res, ctx) => {
    return new Promise((resolve, reject) => {
        if (res.token) {
            localStorage.setItem('token', res.token)
            localStorage.setItem('userId', res.userId)
            localStorage.setItem('userName', res.userName)
            localStorage.setItem('userNumber', res.userNumber)
            actions.userIdGetOrgInfo(ctx).then(()=>{
                resolve()
            }).catch(()=>{
                reject()
            })
            ctx.commit('setUserInfo', {
                ...ctx.state.userInfo,
                ...res
            })
        }
    })
}

let actions = {
    getToken (ctx, userInfo) {
        // 获取token存入localStorage
        // if (localStorage.getItem('userId')) return
        showLoading('加载中...')
        this.msg = '加载中...'
        return new Promise((resolve, reject) => {
            authRequest
                .identityAuthSignin({
                    account: userInfo.account,
                    password: userInfo.password
                })
                .then(res => {
                    setToken(res, ctx).then(()=>{
                        resolve(res)
                    }).catch(err=>{
                        reject(err)
                    })
                })
                .catch(err=>{
                    reject(err)
                })
                .finally(() => {
                    hideLoading()
                    this.msg = ''
                })
        })
    },
    volideToken (ctx, token) {
        if (!token) return
        showLoading('加载中...')
        return  authRequest
            .refreshToken({
                token
            })
            .then(async res => {
                setToken(res, ctx)
            })
            .finally(() => {
                hideLoading()
            })
    },
    async userIdGetOrgInfo (ctx) {
        return new Promise((resolve, reject) => {
            //获取机构信息存入vuex
            const orgId = localStorage.getItem('orgId')
            const userId = localStorage.getItem('userId')
            if (ctx.state.userInfo.orgInfo && Object.keys(ctx.state.userInfo.orgInfo).length !== 0 && (orgId === ctx.state.userInfo.orgInfo.orgId))
                resolve()
            if (!userId) resolve()
            //如果orgId不存在默认取用户第一个机构，如果存在则取当前机构
            authRequest
                .hrOrgGetOrgByUserId({
                    userId
                }).then(res => {
                    // res = [
                    //     {
                    //         'orgId': 'ab7324a9939b-b3ec-ab4e-2932-b69a36a6',
                    //         'orgName': '四川路桥建设集团交通工程有限公司成都至宜宾高速公路设计施工总承包ZCB3、ZCB4标段绿化工程项目经理部',
                    //         'shortCode': 'JTGCCYLHXM',
                    //         'parentId': 'a94220dc350b-b749-9643-a42f-d7303e27',
                    //         'parentName': '四川路桥建设集团交通工程有限公司',
                    //         'orgType': 5
                    //     }
                    // ]
                    if(res.length === 0) {
                        showErrorPop('没有包含机构信息')
                        reject()
                    }else{
                        let orgInfo = []
                        if(orgId) {
                            orgInfo = res.find(x=>x.orgId === orgId)
                        }else{
                            orgInfo = res[0]
                        }
                        localStorage.setItem('orgId', orgInfo.orgId)
                        ctx.commit('setUserInfo', {
                            ...ctx.state.userInfo,
                            orgInfo: orgInfo
                        })
                        authRequest.getOrgById({
                            orgId: orgInfo.orgId
                        }).then(val=>{
                            localStorage.setItem('orgId', val.orgId)
                            ctx.commit('setUserInfo', {
                                ...ctx.state.userInfo,
                                orgInfo: val
                            })
                            ctx.dispatch('getMenuId')
                            resolve()
                        }).catch(()=>{
                            resolve()
                        })
                    }
                }).catch(()=>{
                    reject()
                })
        })

    },
    getBiddingMethod (ctx) {
        //获取招标方式字典存入vuex
        if (Object.keys(ctx.state.biddingApplication.dictionaries.tenderForm).length !== 0) return
        authRequest.configKvGetDicValue({ dicName: '招标方式', isEnable: true }).then(res => {
            res // this.$store.state
            ctx.commit(
                'biddingApplication/updateTenderClass',
                res
                // res.map(value => value.kvKey)
            )
        })
    },
    getCurrency (ctx) {
        //获取币种字典存入vuex
        if (ctx.state.biddingApplication.dictionaries?.currency?.length !== 0) return
        if (!ctx.state.userInfo?.orgInfo?.orgId) return
        return new Promise(resolve => {
            authRequest.configKvGetDicValue1({ dicName: '币种', isEnable: true }).then(res => {
                ctx.commit('biddingApplication/updateCurrencyCategory', res)
                resolve('getCurrency')
            })
        })
    },
    getProfile (ctx) {
        // 获取工程概况存入vuex
        // 切换机构要刷新，所以不需要上面这段
        // if (ctx.state.userInfo.profile && Object.keys(ctx.state.userInfo.profile).length !== 0)
        //     return
        if (!ctx.state.userInfo?.orgInfo?.shortCode) return
        return new Promise(resolve => {
            authRequest
                .profileGetProfile({
                    projectNo: ctx.state.userInfo.orgInfo.shortCode
                })
                .then(res => {
                    ctx.commit('setProfile', res)
                    resolve()
                })
        })
    },
    // 获取机构设置的本位币
    getBaseCyByOrgId (ctx) {
        if (!ctx.state.userInfo?.orgInfo?.orgId) return
        // if (Object.keys(ctx.state.userInfo?.baseCyByOrgId).length !== 0) return
        authRequest.getBaseCyByOrgId({ orgId: ctx.state.userInfo.orgInfo.orgId }).then(res => {
            ctx.commit('setBaseCyByOrgId', res)
        })
    },
    //获取菜单id
    getMenuId (ctx) {
        const menuid = getUrlParams('menuid')
        if(menuid && ctx.state.userInfo.orgInfo && ctx.state.userInfo.orgInfo.orgId) {
            ctx.commit('setMenuid', menuid)
            authRequest.getFunctional({ menuId: menuid }).then(res=>{
                ctx.commit('setPermissions', res.map(x=>x.functionCode))
            })
        }
    }
}

export default actions
